import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.WindowConstants;

public class HelpTopicDialog extends JFrame
{

    private static final long serialVersionUID = 7712304335046640459L;
    private JTextField nameField;
    private JTextArea bodyField;
    private JButton createButton;
    private HelpTopic topic;
    private HelpHandler handler;

    public HelpTopicDialog(HelpTopic ht)
    {
	super(ht.getName());
	this.topic = ht;
	this.nameField = new JTextField(this.topic.getName());
	this.bodyField = new JTextArea(this.topic.getBody());

	this.nameField.setEditable(false);
	this.bodyField.setEditable(false);

	this.setPreferredSize(new Dimension(400, 300));
	this.add(this.nameField, BorderLayout.NORTH);
	this.add(this.bodyField, BorderLayout.CENTER);

	this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
	this.pack();
	this.setVisible(true);
	// forces the window to open in the middle of the screen
	this.setLocationRelativeTo(null);
    }

    public HelpTopicDialog(HelpHandler hh)
    {
	super("New Help Topic");
	this.handler = hh;
	this.nameField = new JTextField("Enter topic name here...");
	this.nameField.addFocusListener(new InstructorUI.ClearTextListener(this.nameField.getText()));
	this.bodyField = new JTextArea("Enter help text here...");
	this.bodyField.addFocusListener(new InstructorUI.ClearTextListener(this.bodyField.getText()));
	this.createButton = new JButton("Create");
	this.setPreferredSize(new Dimension(400, 300));
	this.add(this.nameField, BorderLayout.NORTH);
	this.add(this.bodyField, BorderLayout.CENTER);
	this.add(this.createButton, BorderLayout.SOUTH);
	this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

	this.createButton.addActionListener(new CreateTopicListener());

	this.pack();
	this.setVisible(true);
	// forces the window to open in the middle of the screen
	this.setLocationRelativeTo(null);
	this.createButton.requestFocusInWindow();
    }

    public void createTopic()
    {
	this.handler.generateHelpTopic(this.nameField.getText(), this.bodyField.getText());

    }

    public HelpTopic getTopic()
    {
	return this.topic;
    }

    private class CreateTopicListener implements ActionListener
    {

	@Override
	public void actionPerformed(ActionEvent arg0)
	{
	    HelpTopicDialog.this.createTopic();
	    HelpTopicDialog.this.dispose();
	}

    }

}
